package com.devops.admin.service.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devops.admin.mapper.DOSClusterInfoMapper;
import com.devops.admin.model.DOSCluster;
import com.devops.admin.model.DOSClusterInfo;
import com.devops.admin.service.DOSClusterInfoService;
import com.devops.admin.util.HttpCheckUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName DOSClusterInfoServiceImpl
 * @Description TODO
 * @Author hepingguo
 * @Date 2022/4/28 11:22
 * @Version 1.0
 **/
@Service
public class DOSClusterInfoServiceImpl extends ServiceImpl<DOSClusterInfoMapper, DOSClusterInfo> implements DOSClusterInfoService {
    @Override
    public String getOneAvailableHelmWrapperAPIUrl() {
        String helmWrapperAPIUrl = "";
        List<DOSClusterInfo> dosClusterInfos = list();
        for (DOSClusterInfo dosClusterInfo : dosClusterInfos) {
            String tempHelmWrapperAPIUrl = dosClusterInfo.getHelmWrapperApiUrl();
            //HelmWrapperUrl格式校验
            Assert.isTrue(HttpCheckUtil.isURL(tempHelmWrapperAPIUrl),"HelmWrapperUrl格式不合法");
            //HelmWrapperUrl是否可访问校验
            String result = "";
            try {
                result = HttpUtil.get(tempHelmWrapperAPIUrl,6000);
            } catch (IORuntimeException e) {
                e.printStackTrace();
            } finally {
                if (result.equals("Welcome helm wrapper server")) {
                    helmWrapperAPIUrl = tempHelmWrapperAPIUrl;
                }
            }
            if (StrUtil.isNotBlank(helmWrapperAPIUrl)) {
                break;
            }
        }
        return helmWrapperAPIUrl;
    }

    @Override
    public List<DOSClusterInfo> getClusterInfoAndName() {
       return baseMapper.getClusterInfoAndName();
    }

    @Override
    public DOSClusterInfo getClusterInfoByName(String clusterName) {
        return baseMapper.getClusterInfoByName(clusterName);
    }
}
